package com.l.demo.controller;

import com.l.demo.model.MyUserDo;
import com.l.demo.model.MyUserVo;
import com.l.demo.model.ReqResult;
import com.l.demo.service.MyUserService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.constraints.*;

@RestController
@RequestMapping("auth")
@Validated
public class MyUserController {

    private final MyUserService myUserService;

    public MyUserController(MyUserService myUserService) {
        this.myUserService = myUserService;
    }

    /**
     * 用户登录, 登录成功返回带id的用户信息
     *
     * @param myUserVo 登录信息
     * @return 带id的用户信息或者登录失败原因
     */
    @PostMapping("login")
    public ReqResult login(@RequestBody @Validated MyUserVo myUserVo) {
        // 取用户信息
        MyUserDo userDo = myUserService.getUser(myUserVo.getUsername(), myUserVo.getPassword());
        // 如果用户存在并且密码正确
        if (userDo != null) {
            MyUserVo userVo = new MyUserVo();
            userVo.setUsername(userDo.getUsername());
            userVo.setId(userDo.getId());
            return ReqResult.success(userVo);
        }
        return ReqResult.fail("用户不存在或者密码错误");
    }


    /**
     * 判断用户是否存在
     * @param username 用户名
     * @return
     */
    @GetMapping("exist")
    public ReqResult exist(@RequestParam @NotBlank(message = "用户名不能为空") String username) {
        return ReqResult.success(myUserService.isExist(username));
    }

    /**
     * 用户注册, 注册成功则返回带id的用户信息
     * @param myUserVo 用户信息
     * @return 带id的用户信息或者注册失败的原因
     */
    @PostMapping("register")
    public ReqResult register(@RequestBody @Validated MyUserVo myUserVo) {
        // 用户是否存在
        if (myUserService.isExist(myUserVo.getUsername())) {
            return ReqResult.fail("用户已存在");
        }
        // 注册用户
        MyUserDo userDo = myUserService.registerUser(myUserVo.getUsername(), myUserVo.getPassword());
        if (userDo != null) {
            return ReqResult.success(userDo);
        }
        return ReqResult.fail("注册失败");
    }

    /**
     * 用户登出
     * @param id 用户id
     * @return 成功返回true, 失败返回false
     */
    @GetMapping("logout")
    public ReqResult logout(@RequestParam @Min(value = 1, message = "用户id有误") int id) {
        return ReqResult.success(myUserService.logout(id));
    }
}
